import React, { FunctionComponentElement, useContext, useState } from "react";
import classNames from 'classnames';
import { MenuContext } from './menu';
import { MenuItemProps } from "./menuItem";

const SubMenu: React.FC<SubMenuProps> = ({ 
    index , title, className, children , ...restProps
 }) => {

    const [ menuOpen , setOpen ] = useState(false);
    
    const context = useContext(MenuContext);//

    const classes = classNames('menu-item submenu-item', className, {
        'is-active': Number(context.index) === index 
    });


    

    //设置渲染函数
    const renderChildren = () => {

        const componentReact =  React.Children.map(children, function (child, index) {
            const childrenElement = child as FunctionComponentElement<MenuItemProps>;

            if (childrenElement.type.displayName === 'MenuItem') {
                return childrenElement;
            } else {
                console.error('Warning: childrenElement is not Component');
            }

        });

        return (<ul className="submenu">
            {componentReact}
        </ul>)

    };

    return <li className={classes} key={index} {...restProps}>
        <div className="submenu-title">
            {title}
        </div>
        {renderChildren()}
    </li>;
};

SubMenu.displayName = 'SubMenu';

export interface SubMenuProps {
    title: string,
    index?: number,
    className?: string
}

export default SubMenu;